package com.example.springboot.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.springboot.entity.User;
import com.example.springboot.entity.request.BaseRequest;
import com.example.springboot.entity.request.LoginRequest;
import com.example.springboot.entity.request.PasswordRequest;
import com.example.springboot.exception.ServiceException;
import com.example.springboot.mapper.UserMapper;
import com.example.springboot.service.UserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author 程序员小洋
 * @version 2022.3
 * @date 2022/12/8 11:38
 * @title UserService的业务层
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper,User>implements UserService {

    @Autowired
    private UserMapper userMapper;

    private static final String DEFAULT_PASS = "123";
    private static final String PASS_SALT = "qingge";


    @Override
    public User login(LoginRequest request) {
        User user= null;
        try {
            user = userMapper.getByUsername(request.getUname());
        } catch (Exception e) {
            log.error("根据用户名{} 查询出错", request.getUname());
            throw new ServiceException("用户名错误");
        }
        if (user == null) {
            throw new ServiceException("用户名或密码错误");
        }
        // 判断密码是否合法
        String securePass = securePass(request.getUpwd());
        if (!securePass.equals(user.getUpwd())) {
            throw new ServiceException("用户名或密码错误");
        }
        return user;

    }

    @Override
    public PageInfo<User> pageInfo(BaseRequest baseRequest) {
        PageHelper.startPage(baseRequest.getPageNum(), baseRequest.getPageSize());
        List<User> users = userMapper.listByCondition(baseRequest);
        return new PageInfo<>(users);
    }

    @Override
    public void handleAccount(User user) {
        Integer score = user.getScore();
        if (score == null) {
            return;
        }
        Long id = user.getId();
        User dbUser = userMapper.selectById(id);
        dbUser.setUintegral(dbUser.getUintegral() + score);
        userMapper.updateById(dbUser);
    }

    @Override
    public void changePass(PasswordRequest request) {
        // 注意 你要对新的密码进行加密
        request.setNewPass(securePass(request.getNewPass()));
        int count = userMapper.updatePassword(request);
        if (count <= 0) {
            throw new ServiceException("修改密码失败");
        }
    }

    @Override
    public void saveMD5(User user) {
        // 默认密码 123
        if (StrUtil.isBlank(user.getUpwd())) {
            user.setUpwd(DEFAULT_PASS);
        }
        user.setUpwd(securePass(user.getUpwd()));  // 设置md5加密，加盐
        try {
            userMapper.save(user);
        } catch (DuplicateKeyException e) {
            log.error("数据插入失败， username:{}", user.getUname(), e);
            throw new ServiceException("用户名重复");
        }
    }

    private String securePass(String password) {
        return SecureUtil.md5(password + PASS_SALT);
    }
}
